<!DOCTYPE html>
<html lang="zh-cn">
  <head>
    <meta charset="utf-8" />
    <title>订单列表</title>
    <link rel="stylesheet" href="/app/admin/component/pear/css/pear.css" />
    <link rel="stylesheet" href="/app/admin/admin/css/reset.css" />
  </head>
  <body class="pear-container">
    <!-- 顶部查询表单 -->
    <div class="layui-card">
      <div class="layui-card-body">
        <form class="layui-form top-search-from">

          <input
            type="hidden"
            name="user_id"
            value="<?=$user_id?>"
            class="layui-input"
          />

          <div class="layui-form-item">
            <label class="layui-form-label">订单号</label>
            <div class="layui-input-block">
              <input
                type="hidden"
                autocomplete="off"
                name="order_no[]"
                value="like"
                class="layui-input inline-block"
              />
              <input
                type="text"
                autocomplete="off"
                name="order_no[]"
                class="layui-input"
              />
            </div>
          </div>

          <div class="layui-form-item">
            <label class="layui-form-label">线路</label>
            <div class="layui-input-block">
              <div name="line_id" id="line_id" value=""></div>
            </div>
          </div>

          <div class="layui-form-item">
            <label class="layui-form-label">项目</label>
            <div class="layui-input-block">
              <div name="game_id" id="game_id" value=""></div>
            </div>
          </div>

          <div class="layui-form-item">
            <label class="layui-form-label">时长类型</label>
            <div class="layui-input-block">
              <div name="duration" id="duration" value=""></div>
            </div>
          </div>

          <div class="layui-form-item">
            <label class="layui-form-label">有效期</label>
            <div class="layui-input-block">
              <div name="status" id="status" value=""></div>
            </div>
          </div>

          <div class="layui-form-item">
            <label class="layui-form-label">到期时间</label>
            <div class="layui-input-block">
              <div class="layui-input-block" id="expire_time">
                <input
                  type="text"
                  autocomplete="off"
                  name="expire_time[]"
                  id="expire_time-date-start"
                  class="layui-input inline-block"
                  placeholder="开始时间"
                />
                -
                <input
                  type="text"
                  autocomplete="off"
                  name="expire_time[]"
                  id="expire_time-date-end"
                  class="layui-input inline-block"
                  placeholder="结束时间"
                />
              </div>
            </div>
          </div>

          <div class="layui-form-item layui-inline">
            <label class="layui-form-label"></label>
            <button
              class="pear-btn pear-btn-md pear-btn-primary"
              lay-submit
              lay-filter="table-query"
            >
              <i class="layui-icon layui-icon-search"></i>查询
            </button>
            <button
              type="reset"
              class="pear-btn pear-btn-md"
              lay-submit
              lay-filter="table-reset"
            >
              <i class="layui-icon layui-icon-refresh"></i>重置
            </button>
          </div>
          <div class="toggle-btn">
            <a class="layui-hide"
              >展开<i class="layui-icon layui-icon-down"></i
            ></a>
            <a class="layui-hide"
              >收起<i class="layui-icon layui-icon-up"></i
            ></a>
          </div>
        </form>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="layui-card">
      <div class="layui-card-body">
        <table id="data-table" lay-filter="data-table"></table>
      </div>
    </div>

    <!-- 表格顶部工具栏 -->
    <script type="text/html" id="table-toolbar">
      <button
        plain=""
        class="pear-btn pear-btn-primary pear-btn-md"
        lay-event="remark"
        permission="app.admin.v1order.remark"
      >
        备注
      </button>
    </script>

    <!-- 表格行工具栏 -->
    <script type="text/html" id="table-bar">
      <button
        plain
        class="pear-btn pear-btn-xs pear-btn-primary"
        lay-event="order_node"
        permission="app.admin.v1ordernode.select"
      >
        订单节点
      </button>
      <button
        plain
        class="pear-btn pear-btn-xs pear-btn-primary"
        lay-event="order_node_expire"
        permission="app.admin.v1ordernodeexpire.select"
      >
        节点过期
      </button>
      <!--            <button class="pear-btn pear-btn-xs tool-btn" lay-event="edit" permission="app.admin.v1order.update">编辑</button>-->
      <!--            <button class="pear-btn pear-btn-xs tool-btn" lay-event="remove" permission="app.admin.v1order.delete">删除</button>-->
    </script>

    <script src="/app/admin/component/layui/layui.js?v=2.8.12"></script>
    <script src="/app/admin/component/pear/pear.js"></script>
    <script src="/app/admin/admin/js/permission.js"></script>
    <script src="/app/admin/admin/js/common.js"></script>

    <script>
      let defaultUserId = '<?=$user_id?>'

      // 相关常量
      const PRIMARY_KEY = 'id'
      const SELECT_API = '/app/admin/v1-order/select'
      const UPDATE_API = '/app/admin/v1-order/update'
      const DELETE_API = '/app/admin/v1-order/delete'
      const INSERT_URL = '/app/admin/v1-order/insert'
      const UPDATE_URL = '/app/admin/v1-order/update'

      const REMARK_API = '/app/admin/v1-order/remark'
      const ORDER_NODE_URL = '/app/admin/v1-order-node/index'
      const ORDER_NODE_EXPIRE_URL = '/app/admin/v1-order-node-expire/index'

      // 字段 线路ID line_id
      layui.use(['jquery', 'xmSelect', 'popup'], function () {
        layui.$.ajax({
          url: '/app/admin/v1-line/select2?format=tree',
          data: {
            field: 'weight',
            order: 'desc',
          },
          dataType: 'json',
          success: function (res) {
            let value = layui.$('#line_id').attr('value')
            let initValue = value ? value.split(',') : []
            layui.xmSelect.render({
              el: '#line_id',
              name: 'line_id',
              initValue: initValue,
              filterable: true,
              data: res.data,
              model: { icon: 'hidden', label: { type: 'text' } },
              clickClose: true,
              radio: true,
            })
            if (res.code) {
              layui.popup.failure(res.msg)
            }
          },
        })
      })

      // 字段 游戏ID game_id
      layui.use(['jquery', 'xmSelect', 'popup'], function () {
        layui.$.ajax({
          url: '/app/admin/v1-game/select2?format=tree',
          data: {
            field: PRIMARY_KEY,
            order: 'desc',
          },
          dataType: 'json',
          success: function (res) {
            let value = layui.$('#game_id').attr('value')
            let initValue = value ? value.split(',') : []
            layui.xmSelect.render({
              el: '#game_id',
              name: 'game_id',
              initValue: initValue,
              filterable: true,
              data: res.data,
              model: { icon: 'hidden', label: { type: 'text' } },
              clickClose: true,
              radio: true,
            })
            if (res.code) {
              layui.popup.failure(res.msg)
            }
          },
        })
      })

      // 字段 时长类型 duration
      layui.use(['jquery', 'xmSelect', 'popup'], function () {
        layui.$.ajax({
          url: '/app/admin/dict/getNew/get_duration_type_list',
          dataType: 'json',
          success: function (res) {
            let value = layui.$('#duration').attr('value')
            let initValue = value ? value.split(',') : []
            layui.xmSelect.render({
              el: '#duration',
              name: 'duration',
              initValue: initValue,
              filterable: true,
              data: res.data,
              model: { icon: 'hidden', label: { type: 'text' } },
              clickClose: true,
              radio: true,
            })
            if (res.code) {
              layui.popup.failure(res.msg)
            }
          },
        })
      })

      // 字段 状态:0=未过期,1=已过期 status
      layui.use(['jquery', 'xmSelect', 'popup'], function () {
        layui.$.ajax({
          url: '/app/admin/dict/getNew/get_expire_status_list',
          dataType: 'json',
          success: function (res) {
            let value = layui.$('#status').attr('value')
            let initValue = value ? value.split(',') : []
            layui.xmSelect.render({
              el: '#status',
              name: 'status',
              initValue: initValue,
              filterable: true,
              data: res.data,
              model: { icon: 'hidden', label: { type: 'text' } },
              clickClose: true,
              radio: true,
            })
            if (res.code) {
              layui.popup.failure(res.msg)
            }
          },
        })
      })

      // 字段 到期时间 expire_time
      layui.use(['laydate'], function () {
        layui.laydate.render({
          elem: '#expire_time',
          range: ['#expire_time-date-start', '#expire_time-date-end'],
        })
      })

      // 表格渲染
      layui.use(['table', 'form', 'common', 'popup', 'util'], function () {
        let table = layui.table
        let form = layui.form
        let $ = layui.$
        let common = layui.common
        let util = layui.util

        // 表头参数
        let cols = [
          {
            type: 'checkbox',
            align: 'left',
            width: 50,
          },
          {
            title: '主键',
            align: 'left',
            field: 'id',
            sort: true,
            width: 110,
          },
          {
            title: '订单号',
            align: 'left',
            field: 'order_no',
            width: 220,
          },
          {
            title: '购买用户',
            align: 'left',
            field: 'user_name',
            width: 150,
          },
          {
            title: '线路',
            align: 'left',
            field: 'line_id',
            templet: function (d) {
              let field = 'line_id'
              if (typeof d[field] == 'undefined') return ''
              let items = []
              layui.each((d[field] + '').split(','), function (k, v) {
                items.push(apiResults[field][v] || v)
              })
              return util.escape(items.join(','))
            },
            width: 200,
          },
          {
            title: '项目',
            align: 'left',
            field: 'game_id',
            templet: function (d) {
              let field = 'game_id'
              if (typeof d[field] == 'undefined') return ''
              let items = []
              layui.each((d[field] + '').split(','), function (k, v) {
                items.push(apiResults[field][v] || v)
              })
              return util.escape(items.join(','))
            },
            width: 200,
          },
          {
            title: '时长类型',
            align: 'left',
            field: 'duration',
            templet: function (d) {
              let field = 'duration'
              if (typeof d[field] == 'undefined') return ''
              let items = []
              layui.each((d[field] + '').split(','), function (k, v) {
                items.push(apiResults[field][v] || v)
              })
              return util.escape(items.join(','))
            },
            width: 110,
          },
          {
            title: '数量',
            align: 'left',
            field: 'number',
            width: 100,
          },
          {
            title: '总金币',
            align: 'left',
            field: 'total_amount',
            templet: function (d) {
              if (!d.total_amount) {
                d.total_amount = 0
              }
              return d.total_amount
            },
            width: 100,
          },
          {
            title: '购买时间',
            align: 'left',
            field: 'created_at',
            width: 160,
          },
          {
            title: '到期时间',
            align: 'left',
            field: 'expire_time',
            width: 160,
          },
          {
            title: '来源类型',
            align: 'left',
            field: 'source',
            templet: function (d) {
              let field = 'source'
              if (typeof d[field] == 'undefined') return ''
              let items = []
              layui.each((d[field] + '').split(','), function (k, v) {
                items.push(apiResults[field][v] || v)
              })
              return util.escape(items.join(','))
            },
            width: 100,
          },
          {
            title: '备注',
            align: 'left',
            field: 'remark',
            width: 160,
          },
          {
            title: '操作',
            toolbar: '#table-bar',
            align: 'left',
            fixed: 'right',
            width: 230,
          },
        ]

        // 渲染表格
        function render() {
          table.render({
            elem: '#data-table',
            url: SELECT_API,
            page: true, // 是否显示分页
            limits: [20,100, 200, 300,400,500,600,700,800,900,1000],
            limit: 100, // 每页默认显示的数量
            cols: [cols],
            skin: 'line',
            size: 'lg',
            toolbar: '#table-toolbar',
            autoSort: false,
            defaultToolbar: [
              {
                title: '刷新',
                layEvent: 'refresh',
                icon: 'layui-icon-refresh',
              },
              'filter',
              'print',
              'exports',
            ],
            done: function () {
              layer.photos({ photos: 'div[lay-id="data-table"]', anim: 5 })
              renderDropdown(layui.dropdown)
            },
            where: {
              // 向服务端传递的额外参数
              field: PRIMARY_KEY, // 默认排序的字段
              order: 'desc', // 默认排序方式：asc（升序）或desc（降序）
              user_id: defaultUserId,
            },
            initSort: {
              field: PRIMARY_KEY, // 默认排序的字段
              type: 'desc', // 默认排序方式：asc（升序）或desc（降序）
            },
          })
        }

        // 获取表格中下拉或树形组件数据
        let apis = []
        apis.push(['line_id', '/app/admin/v1-line/select2?format=tree'])
        apis.push(['game_id', '/app/admin/v1-game/select2?format=tree'])
        apis.push(['duration', '/app/admin/dict/getNew/get_duration_type_list'])
        apis.push(['source', '/app/admin/dict/getNew/get_source_type_list'])
        let apiResults = {}
        apiResults['line_id'] = []
        apiResults['game_id'] = []
        apiResults['duration'] = []
        apiResults['source'] = []
        let count = apis.length
        layui.each(apis, function (k, item) {
          let [field, url] = item
          $.ajax({
            url: url,
            dateType: 'json',
            success: function (res) {
              if (res.code) {
                return layui.popup.failure(res.msg)
              }
              function travel(items) {
                for (let k in items) {
                  let item = items[k]
                  apiResults[field][item.value] = item.name
                  if (item.children) {
                    travel(item.children)
                  }
                }
              }
              travel(res.data)
            },
            complete: function () {
              if (--count === 0) {
                render()
              }
            },
          })
        })
        if (!count) {
          render()
        }

        // 编辑或删除行事件
        table.on('tool(data-table)', function (obj) {
          if (obj.event === 'remove') {
            remove(obj)
          } else if (obj.event === 'edit') {
            edit(obj)
          } else if (obj.event === 'order_node') {
            order_node(obj)
          } else if (obj.event === 'order_node_expire') {
            order_node_expire(obj)
          }
        })

        // 表格顶部工具栏事件
        table.on('toolbar(data-table)', function (obj) {
          switch (obj.event) {
            case 'add':
              add()
              break
            case 'refresh':
              refreshTable()
              break
            case 'batchRemove':
              batchRemove(obj)
              break
            // case 'export':
            //   exportTxt(obj)
            //   break
            // case 'copy':
            //   __copy_txt__(obj)
            //   break
            case 'remark':
              remark(obj)
              break
          }
        })

        // 表格顶部搜索事件
        form.on('submit(table-query)', function (data) {
          data.field.field = PRIMARY_KEY
          data.field.order = 'desc'
          console.log(data, 'table-query')
          table.reload('data-table', {
            page: {
              curr: 1,
            },
            where: data.field,
          })
          return false
        })

        // 表格顶部搜索重置事件
        form.on('submit(table-reset)', function (data) {
          let data1 = {}
          data1.field = PRIMARY_KEY
          data1.order = 'desc'
          console.log(data, 'table-reset')
          table.reload('data-table', {
            where: data1,
          })
        })

        // 字段允许为空
        form.verify({
          phone: [/(^$)|^1\d{10}$/, '请输入正确的手机号'],
          email: [
            /(^$)|^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/,
            '邮箱格式不正确',
          ],
          url: [/(^$)|(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/, '链接格式不正确'],
          number: [/(^$)|^\d+$/, '只能填写数字'],
          date: [
            /(^$)|^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$/,
            '日期格式不正确',
          ],
          identity: [
            /(^$)|(^\d{15}$)|(^\d{17}(x|X|\d)$)/,
            '请输入正确的身份证号',
          ],
        })

        // 表格排序事件
        table.on('sort(data-table)', function (obj) {
          let data = obj.config.where
          data.field = obj.field
          data.order = obj.type
          console.log(data, 'obj')
          table.reload('data-table', {
            initSort: obj,
            scrollPos: 'fixed',
            where: data,
            // where: {
            //     field: obj.field,
            //     order: obj.type
            // }
          })
        })

        // 表格新增数据
        let add = function () {
          layer.open({
            type: 2,
            title: '新增',
            shade: 0.1,
            maxmin: true,
            area: [
              common.isModile() ? '100%' : '60%',
              common.isModile() ? '100%' : '95%',
            ],
            content: INSERT_URL,
            skin: '',
          })
        }

        // 表格编辑数据
        let edit = function (obj) {
          let value = obj.data[PRIMARY_KEY]
          layer.open({
            type: 2,
            title: '修改',
            shade: 0.1,
            maxmin: true,
            area: [
              common.isModile() ? '100%' : '60%',
              common.isModile() ? '100%' : '95%',
            ],
            content: UPDATE_URL + '?' + PRIMARY_KEY + '=' + value,
            skin: '',
          })
        }

        // 删除一行
        let remove = function (obj) {
          return doRemove(obj.data[PRIMARY_KEY])
        }

        // 删除多行
        let batchRemove = function (obj) {
          let checkIds = common.checkField(obj, PRIMARY_KEY)
          if (checkIds === '') {
            layui.popup.warning('未选中数据')
            return false
          }
          doRemove(checkIds.split(','))
        }

        // 执行删除
        let doRemove = function (ids) {
          let data = {}
          data[PRIMARY_KEY] = ids
          layer.confirm(
            '确定删除?',
            {
              icon: 3,
              title: '提示',
            },
            function (index) {
              layer.close(index)
              let loading = layer.load()
              $.ajax({
                url: DELETE_API,
                data: data,
                dataType: 'json',
                type: 'post',
                success: function (res) {
                  layer.close(loading)
                  if (res.code) {
                    return layui.popup.failure(res.msg)
                  }
                  return layui.popup.success('操作成功', refreshTable)
                },
              })
            }
          )
        }

        // 刷新表格数据
        window.refreshTable = function () {
          table.reloadData('data-table', {
            scrollPos: 'fixed',
            done: function (res, curr) {
              if (curr > 1 && res.data && !res.data.length) {
                curr = curr - 1
                table.reloadData('data-table', {
                  page: {
                    curr: curr,
                  },
                })
              }
            },
          })
        }

        // 备注
        let remark = function (obj) {
          let checkIds = common.checkField(obj, PRIMARY_KEY)
          if (checkIds === '') {
            layui.popup.warning('未选中数据')
            return false
          }
          doRemark(checkIds.split(','))
        }

        // 执行备注
        let doRemark = function (ids) {
          let data = {}
          data[PRIMARY_KEY] = ids

          layer.prompt({ title: '请输入备注' }, function (value1, index, elem) {
            let remark = value1
            if (remark === '') {
              return layui.popup.failure('请输入备注')
            }

            layer.close(index)
            let loading = layer.load()
            $.ajax({
              url: REMARK_API,
              data: { id: ids, remark: remark },
              dataType: 'json',
              type: 'post',
              success: function (res) {
                layer.close(loading)
                if (res.code) {
                  return layui.popup.failure(res.msg)
                }
                return layui.popup.success('操作成功', refreshTable)
              },
              error: function () {
                layer.close(loading)
                return layui.popup.failure('网络错误')
              },
            })
          })
        }

        // 订单节点
        let order_node = function (obj) {
          let value = obj.data[PRIMARY_KEY]
          layer.open({
            type: 2,
            title: '订单节点',
            shade: 0.1,
            maxmin: true,
            area: [
              common.isModile() ? '100%' : '98%',
              common.isModile() ? '100%' : '95%',
            ],
            content: ORDER_NODE_URL + '?order_id=' + value,
            skin: '',
          })
        }

        // 节点过期
        let order_node_expire = function (obj) {
          let value = obj.data[PRIMARY_KEY]
          layer.open({
            type: 2,
            title: '节点过期',
            shade: 0.1,
            maxmin: true,
            area: [
              common.isModile() ? '100%' : '98%',
              common.isModile() ? '100%' : '95%',
            ],
            content: ORDER_NODE_EXPIRE_URL + '?order_id=' + value,
            skin: '',
          })
        }

        /*-------按钮操作----------*/
        //   导出选中数据文本
        let exportTxt = function (obj) {
          let data = table.checkStatus(obj.config.id).data
          if (!data || !data.length) return layui.popup.warning('未选中数据')
          openExportData(data)
          // const dataStr = data
          //   .map(
          //     (item) =>
          //       `${item.ip}|${item.port}|${item.account}|${item.pass}|${item.expire_time}`
          //   )
          //   .join('\n')
          // downloadTextAsFile(dataStr)
        }

        //   复制选中数据 格式 xx|xx|xx|xx
        let __copy_txt__ = function (obj) {
          let data = table.checkStatus(obj.config.id).data
          if (!data || !data.length) return layui.popup.warning('未选中数据')
          const dataStr = data
            .map(
              (item) =>
                `${item.ip}|${item.port}|${item.account}|${item.pass}|${item.expire_time}`
            )
            .join('\n')
          copyText(dataStr)
        }
      })
    </script>
  </body>
</html>
